package com.lmc.chatroom.controller;

import com.lmc.chatroom.model.Friend;
import com.lmc.chatroom.model.MessageSession;
import com.lmc.chatroom.model.Result;
import com.lmc.chatroom.model.User;
import com.lmc.chatroom.service.sessionService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/session")
public class SessionController {

    @Autowired
    private sessionService sessionService;

    @RequestMapping("/getSessions")
    public Result getSessions(HttpServletRequest request) {
        log.info("getSessions");
        HttpSession session = request.getSession(false);
        if(session == null){
            log.info("客户端页面获取session失败，session为空");
            return Result.fail("获取用户好友列表失败");
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            log.info("客户端页面获取session失败，user为空");
            return Result.fail("获取用户好友列表失败");
        }
//        获取到会话id以及各会话的好友
        List<MessageSession> sessionList = sessionService.selectSessionsByUserId(user.getUserId());

        log.info("用户"+user.getUsername()+"的会话列表为"+sessionList.toString());
        return Result.success(sessionList);
    }

    @RequestMapping("/createsession")
    public Result createSessions(Integer friendId,HttpServletRequest request) {
        log.info("createsession");
        HttpSession session = request.getSession(false);
        if(session == null){
            log.info("服务端获取session失败，session为空");
            return Result.fail("创建新会话失败");
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            log.info("服务端获取session失败，user为空");
            return Result.fail("创建新会话失败");
        }
//        获取到会话id以及各会话的好友
        Integer sessionId = sessionService.creatSession(user.getUserId(),friendId);
        log.info("新建会话sessionId为"+sessionId.toString());
        return Result.success(sessionId);
    }

}
